<template>
  <div class="main">
    <vue3-seamless-scroll
      :list="HeadcountList"
      class="seamless_wrap"
      :hover="true"
      :limitScrollNum="25"
      :step="0.5"
    >
      <div class="grid">
        <template v-for="item,index in HeadcountList" :key="index">
          <div class="item" v-if="item.status != -1">
            <div class="userInfo">
              <div class="top">
                <span class="class_name">{{
                  item.className ? item.className : "暂无信息"
                }}</span>
                <span
                  :class="{
                    status: item.status == 1,
                    status_nosign: item.status == 0,
                  }"
                  >{{ item.status == 1 ? "已签到" : "未签到" }}</span
                >
              </div>
              <!-- 整个人脸图片 -->
              <img
                :src="item.faceUrl"
                class="faceImg"
                alt=""
                v-if="item.status == 1"
              />
              <img
                src="../../assets/images/samll@2x.png"
                class="faceImg"
                alt=""
                v-else
              />
              <!-- 底部的个人信息 -->
              <div
                class="bottom"
                :class="{
                  bottom_bj1: item.status == 1,
                  bottom_bj2: item.status == 0,
                }"
              >
                <img
                  v-if="item.status == 1"
                  src="../../assets/images/fzds@2x.png"
                  class="fzdsImg"
                  alt=""
                />
                <img
                  v-else
                  src="../../assets/images/fzds.png"
                  class="fzdsImg"
                  alt=""
                />
                <div class="user_dec">
                  <div class="userName">{{ item.name }}</div>
                  <div class="clockTime" v-if="item.status == 1">
                    {{ item.clockTime }}
                  </div>
                  <div class="clockTime" v-else>{{ comTime }}</div>
                </div>
              </div>
            </div>
            <div class="empty_img" v-if="item.id == null">
              <img src="../../assets/images/samll@2x.png" alt="" />
            </div>
          </div>
          <div class="item" v-else>
            <div class="empty_img">
              <img src="../../assets/images/samll@2x.png" alt="" />
            </div>
          </div>
        </template>
      </div>
    </vue3-seamless-scroll>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
// import WebSocket from "websocket";
import { Vue3SeamlessScroll } from "vue3-seamless-scroll";
// 滚动的配置项
const classOption = ref({
  step: 0.6, // 数值越大速度滚动越快
  limitMoveNum: 25, // 开始无缝滚动的数据量 this.dataList.length
  hoverStop: true, // 是否开启鼠标悬停stop
  direction: 1, // 0向下 1向上 2向左 3向右
  openWatch: true, // 开启数据实时监控刷新dom
  singleHeight: 0, // 单步运动停止的高度(默认值0是无缝不停止的滚动) direction => 0/1
  singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动) direction => 2/3
  waitTime: 1000, // 单步运动停止的时间(默认值1000ms)
});

const route = useRoute();
const router = useRouter();
// 记录不滚动的数量
const scrollTop = ref(24);
// 记录空的数据
const emptyNum = ref(0);
const HeadcountList = ref([
  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 0,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 0,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 0,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 0,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 0,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 0,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },  {
    id: 1,
    name: "张三",
    faceUrl: "https://ruan30-1318331856.cos.ap-guangzhou.myqcloud.com/tx.png",
    // 打卡时间
    clockTime: "2021-12-12 12:12:12",
    className: "20计算机科学与技术1班",
    status: 1,
  },
]);
// 监听的用户id
const userId = ref(null);
// 初始化websocket
const socket = ref(null);
const initWebsocket = () => {
  if (!window.WebSocket) {
    alert("您的浏览器不支持WebSocket");
  } else {
    // 获取ip地址或者域名
    const ip = location.hostname;
    const wsIP = "ws://" + ip + ":8080";
    socket.value = new WebSocket(wsIP); // 替换为你的 WebSocket 服务器地址
    // socket.value = new WebSocket("ws://127.0.0.1:8080"); // 替换为你的 WebSocket 服务器地址

    socket.value.onopen = () => {
      console.log("WebSocket 连接已建立");
      // 开启心跳
      heartBeat();
      // 在连接建立后，可以发送消息或执行其他操作
      // socket.value.send(
      //   JSON.stringify({
      //     event: "DateScreen",
      //     data: {
      //       uid: userId.value,
      //     },
      //   })
      // );
    };

    socket.value.onmessage = (event) => {
      isReconnect.value = true;
      console.log("收到消息:", event.data);
      const jsonData = JSON.parse(event.data);
      // 处理收到的消息数据
      if (jsonData.event == "message") {
        const data = jsonData.data;
        // 找到数据的位置 根据名字
        const index = HeadcountList.value.findIndex((item) => {
          return item.name == data.name;
        });
        HeadcountList.value.splice(index, 1);
        HeadcountList.value.unshift(data);
      }
      if (jsonData.event == "sentSign") {
        const data = jsonData.data;
        console.log(data, "发布签到后的结果");
        // 调用处理结果函数
        handleSignResult(data);
      }
      // 收到消息: {"event":"message","data":{"id":"8e77a95d-30f3-4ed1-8fc4-5146c7eac928","name":"小小真","faceUrl":"https://ruan-cso-1318331856.cos.ap-guangzhou.myqcloud.com/face/%E5%B0%8F%E5%B0%8F%E7%9C%9Fsign.jpeg","clockTime":"2023/11/21 13:47:50","className":"俄语","status":1}}
    };

    socket.value.onclose = () => {
      console.log("WebSocket 连接已关闭");
      isReconnect.value = false; //连接都关闭了肯定要重新连接
      reconnect();
      // 在连接关闭后，可以执行清理操作或重新连接等处理
    };
  }
};

// 处理未签到的结果的
const handleSignResult = (data) => {
  const no_sign = data.map((item) => {
    const obj = {
      id: item.id,
      name: item.u_name,
      faceUrl: "",
      // 打卡时间
      clockTime: item.updatedAt,
      className: "暂无班级信息",
      status: 0,
    };
    return obj;
  });
  // 从第几位开始
  let begin = scrollTop.value - emptyNum.value;
  /**
   * 方案er
   * 删除所有空的然后再放进去
   */

  HeadcountList.value.splice(begin, emptyNum.value);
  HeadcountList.value = [...HeadcountList.value, ...no_sign];
  console.log(HeadcountList.value, "处理好的数据");
  // 调用补全24个占位符
  complete24();
};

// 补全24占位
const complete24 = () => {
  if (HeadcountList.value.length >= 24) {
    emptyNum.value = 0;
    return;
  }
  const num = 24 - HeadcountList.value.length;
  emptyNum.value = num;
  for (let i = 0; i < num; i++) {
    const obj = {
      id: new Date().getTime() + "" + i,
      name: "",
      faceUrl: "",
      // 打卡时间
      clockTime: "",
      className: "",
      status: -1,
    };
    HeadcountList.value.push(obj);
  }
};

// 计算时间的属性
const comTime = computed(() => {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth() + 1;
  const day = now.getDate();
  const hour = now.getHours();
  const minute = now.getMinutes();
  const second = now.getSeconds();
  return `
    ${year.toString()}-
    ${month.toString().padStart(2, "0")}-
    ${day.toString().padStart(2, "0")} 
    ${hour.toString().padStart(2, "0")}:
    ${minute.toString().padStart(2, "0")}:
    ${second.toString().padStart(2, "0")}
  `;
});

// 存放心跳定时器
const heartBeatTimer = ref(null);
// 存放错误心跳定时器
const heartBeatErrorTimer = ref(null);
// 开启心跳
const heartBeat = () => {
  // 每 50 秒发送一次心跳
  const heartBeatTime = 50 * 1000;
  // 心跳包
  const heartBeatData = {
    event: "heartBeat",
    data: {},
  };
  heartBeatTimer.value && clearInterval(heartBeatTimer.value);
  heartBeatTimer.value = setInterval(() => {
    socket.value.send(JSON.stringify(heartBeatData));
    // 如果20s收不到消息要么断开要么后端出错
    setTimeout(() => {
      isReconnect.value = false;
      reconnect();
    }, 20 * 1000);
  }, heartBeatTime);
};
// 是否需要重连的开关  true 表示不需要重连
const isReconnect = ref(false);
// 重新连接
const reconnect = () => {
  if (isReconnect.value) {
    return;
  }
  isReconnect.value = true;
  // 关闭当前连接
  socket.value.close();
  // 等待1s后重新连接
  heartBeatErrorTimer.value = setTimeout(() => {
    initWebsocket();
  }, 1000);
};

onMounted(() => {
  //console.log('3.-组件挂载到页面之后执行-------onMounted')
  // 先从缓存中获取id
  const JsonUser = sessionStorage.getItem("user");
  const uid = JSON.parse(JsonUser) !== null ? JSON.parse(JsonUser).id : "游客";
 
  userId.value = uid;
  ElMessage({
    message: "欢迎 各位游客 您的到来！",
    type: "success",
  });

  initWebsocket();
  complete24();
});
onBeforeUnmount(() => {
  if (socket.value) {
    socket.value.close(); // 在组件销毁前关闭 WebSocket 连接
  }
  heartBeatTimer.value && clearInterval(heartBeatTimer.value);
});
</script>
<style scoped lang="scss">
.main {
  margin: 20px 0;
  color: white;

  .seamless_wrap {
    height: 2160px;
    width: 3840px;
    overflow: hidden;
    // margin-bottom: 30px;
    .grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, 452px);
      grid-template-rows: repeat(auto-fill, 670px);
      grid-gap: 15px;
      // 居中
      justify-content: center;
      .item {
        .userInfo {
          width: 452px;
          height: 670px;
          border-radius: 20px;
          position: relative;
          overflow: hidden;
          .top {
            width: 100%;
            height: 100px;
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            background-image: url("../../assets/images/wg4@2x.png");
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            flex-wrap: nowrap;
            .class_name {
              flex: 3;
              font-size: 30px;
              font-family: PingFangSC, PingFang SC;
              font-weight: 600;
              color: #ffffff;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              margin-right: 10px;
            }
            .status {
              flex: 1;
              font-size: 30px;
              font-family: PingFangSC, PingFang SC;
              font-weight: 600;
              color: #1bb7ff;
            }
            .status_nosign {
              flex: 1;
              font-size: 30px;
              font-family: PingFangSC, PingFang SC;
              font-weight: 600;
              color: #e8870f;
            }
          }
          .faceImg {
            width: 452px;
            height: 670px;
          }
          .bottom_bj1 {
            background: linear-gradient(226deg, #0043c4 0%, #007fda 100%);
          }
          .bottom_bj2 {
            background: linear-gradient(226deg, #ec560f 0%, #e88c0f 100%);
          }
          .bottom {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            width: 100%;
            height: 120px;
            display: flex;
            align-items: center;
            .fzdsImg {
              width: 90px;
              height: 90px;
              margin-left: 30px;
            }
            .user_dec {
              margin-left: 15px;
              .userName {
                font-size: 32px;
                font-family: PingFangSC, PingFang SC;
                font-weight: 600;
                color: #ffffff;
                margin-bottom: 10px;
              }
              .clockTime {
                font-size: 20px;
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                color: #ffffff;
              }
            }
          }
        }
        .empty_img {
          img {
            width: 452px;
            height: 670px;
          }
        }
      }
    }
  }
}
</style>
